<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background-color: rgb(251, 251, 251);
        }

        img {
            width: 300px;
            height: 300px;
            position: absolute;
            left: 0;
            top: 50%;
        }
    </style>
</head>

<body>

    <img src="./小熊.gif" alt="">
    <script>
        var img = document.querySelector('img')
        var w;
        var imgLeft;
        var imgWidth;
        var len = 10;
        window.onload = function () {
            imgLeft = img.offsetLeft
            // console.log(imgLeft);
            imgWidth = img.width
            w = window.innerWidth
            console.log(imgLeft, imgWidth, w);
            move()
        }


        function move() {
            
            if (imgLeft < 0 || imgLeft + imgWidth > w) {
                len = -len
            }


            img.style.left = imgLeft + len + 'px'
            imgLeft = img.offsetLeft
            setTimeout(move)
        }
    </script>
</body>

</html>